import 'dart:io';

import 'package:dio/dio.dart';
import 'package:flutter/material.dart';
import 'package:flutter_juwo/common/common_index.dart';
import 'package:flutter_juwo/ui/pages/personalCenterPages/representation/model/up_image_entity.dart';
import 'package:flutter_juwo/ui/pages/photoHero/PhotoHeroNet.dart';
import 'package:flutter_juwo/ui/pages/photoHero/showBigImageNet.dart';
import 'package:flutter_juwo/ui/res/strings.dart';
import 'package:flutter_juwo/ui/utils/image_compress_utils.dart';
import 'package:flutter_juwo/ui/utils/select_pic.dart';
import 'package:flutter_juwo/ui/utils/toast_utils.dart';
import 'package:flutter_juwo/ui/utils/utils.dart';
import 'package:image_picker/image_picker.dart';
import 'package:permission_handler/permission_handler.dart';

import 'LoadingDialog.dart';
import 'judje_dialog.dart';

///封装选择图片的组件
///@num 传入最大图片数 ]
///可选 imgUrls 传入直接显示
///@onComlete 完成时回调
class SelectShowPicWidget extends StatefulWidget {
  int num;
  Function(List<String>) onComplete;
  List<String> imgUrls;
  bool isHead;

  SelectShowPicWidget(this.num, this.onComplete, {this.imgUrls, this.isHead});

  @override
  _SelectShowPicWidgetState createState() => _SelectShowPicWidgetState();
}

class _SelectShowPicWidgetState extends State<SelectShowPicWidget> {
  @override
  void initState() {
    // TODO: implement initState
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return getPicList();
  }

  getPicList() {
    if (widget.imgUrls.length <= 0) {
      return Container(
        alignment: Alignment.centerLeft,
        child: getImageAdd(),
      );
    } else {
      return GridView.count(
        physics: NeverScrollableScrollPhysics(),
        shrinkWrap: true,
        //水平子Widget之间间距
        crossAxisSpacing: ScreenUtil().setWidth(30),
        //垂直子Widget之间间距
        mainAxisSpacing: 5.0,
        //GridView内边距
        padding: EdgeInsets.all(2.0),
        //一行的Widget数量
        crossAxisCount: 1,
        //子Widget宽高比例
        childAspectRatio: 1.0,
        //子Widget列表
        children: getWidgetList(),
      );
    }
  }

  List<Widget> getWidgetList() {
    if (widget.imgUrls.length == widget.num) {
      return widget.imgUrls.map((item) => getItemContainer(item)).toList();
    } else {
      return widget.imgUrls.map((item) => getItemContainer(item)).toList()
        ..add(getImageAdd());
    }
  }

  Widget getItemContainer(String url) {
    return Container(
        child: widget.isHead
            ? InkWell(
                onTap: () {
                  getImage();
                },
                child: ClipOval(
                    child: UiUtils.cachedNetworkImage(
                  120,
                  120,
                  url,
                )),
              )
            : Stack(
                children: <Widget>[
                  PhotoHeroNet(
                      photo: url,
                      onTap: () {
                        Navigator.push(
                          context,
                          MaterialPageRoute(
                              builder: (context) => ShowBigImagePageNet(url)),
                        );
                      },
                      width: 300),
                  Positioned(
                      left: 40.0,
                      right: 0,
                      top: 0.0,
                      child: InkWell(
                        onTap: () {
                          setState(() {
                            int index = widget.imgUrls.indexOf(url);
                            widget.imgUrls.removeAt(index);
                            widget.onComplete(widget.imgUrls);
                          });
                        },
                        child: Image.asset(
                          Utils.getImgPath('icon_delete01'),
                          width: 20.0,
                          height: 20.0,
                        ),
                      ))
                ],
              ));
  }

  getImageAdd() {
    return InkWell(
      onTap: () {
        getImage();
      },
      child: widget.isHead ? SelectPic.selectHead : SelectPic.selectPic,
    );
  }

  Future getImage() async {
/*    var image = await ImagePicker.pickImage(source: ImageSource.gallery);

    if (image != null) {
      showDialog(
          context: context,
          barrierDismissible: false,
          builder: (BuildContext context) {
            return LoadingDialog(
              text: "上传中",
            );
          });
      _upLoadImage(image);
    }*/

    // 申请权限
    Map<PermissionGroup, PermissionStatus> permissions =
        await PermissionHandler().requestPermissions([PermissionGroup.storage]);

    // 申请结果  权限检测
    PermissionStatus permission = await PermissionHandler()
        .checkPermissionStatus(PermissionGroup.storage);

    if (permission == PermissionStatus.granted) {
      //权限申请通过
      var image = await ImagePicker.pickImage(source: ImageSource.gallery);
      if (image != null) {
        showDialog(
            context: context,
            barrierDismissible: false,
            builder: (BuildContext context) {
              return LoadingDialog(
                text: "上传中",
              );
            });
        _upLoadImage(image); //上传图片
      }
    } else {
      showElasticDialog(
          context: context,
          builder: (BuildContext context) {
            return JudjeDialog(
              title: "没有访问存储权限",
              value: Strings.NO_PERMISSION_MSG,
              onPressed: () async {
                NavigatorUtils.goBack(context);
                //权限申请被拒绝！
                bool isOpened = await PermissionHandler().openAppSettings();
                if (isOpened) {
                  print("打开设置页面");
                } else {
                  ToastUtil.showShortToast("");
                }
              },
            );
          });
    }

    //上传图片
  }

  _upLoadImage(File image) async {
    print("image.absolute.path");

    ///压缩图片
    File result = await CompressImage.testCompressAndGetFile(image, image.path);
    String path = result.path;
    var name = path.substring(path.lastIndexOf("/") + 1, path.length);
    FormData formData =
        new FormData.from({"pic": new UploadFileInfo(new File(path), name)});
    DioManager.getInstance().post(Api.USER_UPLODIMG, formData, (json) {
      UpImageEntity entity = UpImageEntity.fromJson(json);

      ///上传失败
      if (entity == null) {
        ToastUtil.showShortErrToast(Api.ERR_NOTHING);
        return;
      }
      if (entity.status != "200") {
        ToastUtil.showShortErrToast(entity.message);
        return;
      }

      ///上传 成功 显示图片
      if (entity.status == "200") {
        widget.imgUrls.add(entity.data);
        widget.onComplete(widget.imgUrls);
        setState(() {});
      }
      NavigatorUtils.goBack(context);

      print("上传成功：$json");
    }, (err) {
      NavigatorUtils.goBack(context);
      print("上传失败：$err");
    });
  }
}
